package com.zxm.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.ibatis.scripting.xmltags.StaticTextSqlNode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.dubbo.config.annotation.Service;
import com.zxm.mapper.ContentCategoryMapper;
import com.zxm.pojo.ContentCategory;
import com.zxm.pojo.ContentCategoryExample;
import com.zxm.result.GuhealthResult;
import com.zxm.result.TreeResult;
import com.zxm.service.ContentCategoryService;

import junit.runner.BaseTestRunner;

@Service(interfaceName="com.zxm.service.ContentCategoryService")
public class ContentCategoryServiceImpl implements ContentCategoryService {

	@Autowired
	private ContentCategoryMapper contentCategoryMapper;
	
	private static final Logger logger = LoggerFactory.getLogger(ContentCategoryServiceImpl.class);
	
	/**
	 * 获得树形结构
	 */
	@Override
	public List<TreeResult> getTree(Long pId) {
		pId = (pId==null)?0:pId;
		ContentCategoryExample example = new ContentCategoryExample();
		example.createCriteria().andParentIdEqualTo(pId).andStatusEqualTo(1);
		List<ContentCategory> contentList = contentCategoryMapper.selectByExample(example);
		List<TreeResult> result = new ArrayList<>();
		for(ContentCategory category:contentList) {
			TreeResult res = new TreeResult();
			res.setId(category.getId().intValue());
			res.setState(category.getIsParent()==1?"closed":"open");
			res.setText(category.getName());
			result.add(res);
		}
		return result;
	}

	/**
	 * 更新或者保存添加
	 */
	@Override
	public GuhealthResult saveOrUpdate(ContentCategory category) {
		try {
			Long id = category.getId();
			category.setUpdated(new Date());
			int res = 0;
			if(id != null && id>0) {
				//更新操作
				res = contentCategoryMapper.updateByPrimaryKeySelective(category);
			}else {
				//保存添加操作 是否为父类目，1为true 0为false
				category.setIsParent((byte)0);
				category.setCreated(new Date());
				//排序序号
				category.setSortOrder(1);
				// 状态1(正常)，2（删除）
				category.setStatus(1);
				res = contentCategoryMapper.insertSelective(category);
				//添加完成后，应该根据parentId将父节点的isParent改为1
				ContentCategory parent = contentCategoryMapper.selectByPrimaryKey(category.getParentId());
				parent.setIsParent((byte)1);
				contentCategoryMapper.updateByPrimaryKeySelective(parent);
			}
			if(1==res) {
				return GuhealthResult.success();
			}
		} catch (Exception e) {
			logger.error("商品内容操作失败，原因:"+e.getMessage());
		}
		return GuhealthResult.fail();
	}

	/**
	 * 删除
	 */
	@Override
	public GuhealthResult deleteById(Long id) {
		try {
			ContentCategory contentCategory = new ContentCategory();
			contentCategory.setId(id);
			contentCategory.setStatus(2);
			contentCategoryMapper.updateByPrimaryKeySelective(contentCategory);
			ContentCategory content = contentCategoryMapper.selectByPrimaryKey(id);
			if(content.getIsParent()== (byte)1) {
				delChildren(contentCategory.getId());
			}
			return GuhealthResult.success();
		} catch (Exception e) {
			logger.error("内容删除失败，原因："+e.getMessage());
		}
		return GuhealthResult.fail();
	}
	/**
	 * 修改isParent==1的节点的子节点的状态
	 * @param id
	 */
	private void delChildren(Long id) {
		System.out.println("delChildren"+id);
		ContentCategoryExample example = new ContentCategoryExample();
		example.createCriteria().andParentIdEqualTo(id);
		List<ContentCategory> chirdren = contentCategoryMapper.selectByExample(example);
		System.out.println("child:"+chirdren.size());
		if(chirdren!=null && chirdren.size()>0) {
			for(ContentCategory category:chirdren) {
				deleteById(category.getId());
			}
		}
		
	}

	/**
	 * 根据分类名称查询类目
	 */
	@Override
	public List<ContentCategory> findCatsByName(String catName) {
		ContentCategoryExample example = new ContentCategoryExample();
		example.createCriteria().andNameEqualTo(catName);
		return contentCategoryMapper.selectByExample(example);
	}

}
